package com.example.core.utils;

import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class VerifyUtils {

    private static final String VERIFY_CODES = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
    private static final String NUMBER_VERIFY_CODES = "1234567890";

    public static boolean checkPhone(String phone) {
        Pattern regex = Pattern.compile("^1[2|3|4|5|6|7|8|9][0-9]\\d{8}$");
        Matcher m = regex.matcher(phone);
        return m.matches();
    }

    /**
     * 使用系统默认字符源生成验证码：纯数字
     *
     * @param verifySize 验证码长度
     * @return
     */
    public static String generateNumberVerifyCode(int verifySize) {
        return generateVerifyCode(verifySize, NUMBER_VERIFY_CODES);
    }

    /**
     * 使用指定源生成验证码
     *
     * @param verifySize 验证码长度
     * @param sources    验证码字符源
     * @return
     */
    private static String generateVerifyCode(int verifySize, String sources) {
        if (sources == null || sources.isEmpty()) {
            sources = VERIFY_CODES;
        }
        int codesLen = sources.length();
        Random rand = new Random(System.currentTimeMillis());
        StringBuilder verifyCode = new StringBuilder(verifySize);
        for (int i = 0; i < verifySize; i++) {
            verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
        }
        return verifyCode.toString();
    }
}
